package ch.rheintalconnection.sysventory.presentation.panels;

import ch.rheintalconnection.sysventory.application.ScanCommand;
import ch.rheintalconnection.sysventory.businessServices.ScanningService;
import ch.rheintalconnection.sysventory.domain.User;

import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

public class ScanPanel extends VerticalLayout implements Button.ClickListener {

	private static final long serialVersionUID = -5754846780511819947L;

	private TextField ipInput1;
	private TextField ipInput2;
	private TextField ipInput3;
	private TextField ipInput4;
	private TextField subnetInput;
	private Label infoLabel;
	private ScanCommand scanCommand;

	private User user;

	public ScanPanel(ScanningService scanningService) {

		scanCommand = new ScanCommand(scanningService);

		HorizontalLayout ipLayout = new HorizontalLayout();
		this.addComponent(ipLayout);

		Button btnScan = new Button("Scan Starten");
		btnScan.addListener(this);

		ipInput1 = new TextField();
		ipInput2 = new TextField();
		ipInput3 = new TextField();
		ipInput4 = new TextField();
		subnetInput = new TextField();
		infoLabel = new Label();

		Label point1 = new Label(".");
		Label point2 = new Label(".");
		Label point3 = new Label(".");
		Label slash = new Label("/");

		// ipField1.setWidth(100, UNITS_PERCENTAGE);

		ipLayout.addComponent(ipInput1);
		ipLayout.addComponent(point1);
		ipLayout.addComponent(ipInput2);
		ipLayout.addComponent(point2);
		ipLayout.addComponent(ipInput3);
		ipLayout.addComponent(point3);
		ipLayout.addComponent(ipInput4);
		ipLayout.addComponent(slash);
		ipLayout.addComponent(subnetInput);
		ipLayout.addComponent(btnScan);

		this.addComponent(infoLabel);

	}

	public void buttonClick(ClickEvent event) {

		String sIpMask = ipInput1.getValue() + "." + ipInput2.getValue() + "." + ipInput3.getValue() + "." + ipInput4.getValue();
		sIpMask += "/" + subnetInput.getValue();

		if (scanCommand.validateIpMask(sIpMask)) {

			if (user.getRolle() == 1) {
				int iCount = scanCommand.scan(sIpMask, user);
				setInformation("Es wurden " + iCount + " Computer gescannt.");
			} else {
				setInformation("Sie sind nicht als Administrator angemeldet und haben keine Berechtigung \n\r einen Scan auszuführen.");
			}

		} else {
			setInformation("Es wurde ein ungültiger IP-Bereich eingegeben.");
		}
	}

	private void setInformation(String sInfo) {
		infoLabel.setValue(sInfo);
	}

	public void setUser(User user) {
		this.user = user;

	}

}
